package com.alan.nio.nionetwork;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Scanner;

/**
 * 使用NIO完成网络通信的三个核心
 *
 * Buffer:负责数据的存储
 * Channel:负责连接
 * Selector：多路复用器，监控SelectableChannel的
 *
 * Created by Alan on 2017/8/10.
 */
public class Client {

    public static void main(String[] args) throws IOException {
        // 1.获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));

        // 2.把通道切换为非阻塞
        socketChannel.configureBlocking(false);

        // 3.分配指定大小的缓存区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 4.准备接受键盘输入
        Scanner in = new Scanner(System.in);

        while (in.hasNext()){
            String string = in.nextLine();
            buffer.put((new Date().toString() + "\n"+string).getBytes());
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
        socketChannel.close();
    }

}
